<template>
  <div class='app-container multi-footer'>
		<el-select v-model="queryParams.year" placeholder="请选择" size="small" @change="getData()">
        <el-option
          v-for="item in years"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
			<div class="filter-container">
      <el-button
        type="primary"
        size="mini"
        plain
        icon="el-icon-plus"
				@click="handleAdd()"
      >
        新增
      </el-button>
      <el-button
        type="success"
        size="mini"
        plain
        icon="el-icon-edit"
        :disabled="buttonState.editDisabled"
				@click="handleUpdate()"
      >
        修改
      </el-button>
      <el-button
        type="danger"
        size="mini"
        plain
        icon="el-icon-delete"
        :disabled="buttonState.delDisabled"
				@click="handleDelete()"
      >
        删除
      </el-button>
      <right-toolbar @queryTable="getData"></right-toolbar>
    </div>
		<el-table
      :data="tableData"
      style="width: 100%"
      ref="benefitTable"
      v-loading="loading"
			@selection-change="handleSelectionChange"
			show-summary
      :summary-method="getSummaries"
			@sort-change='sortChange'
			:default-sort = "{prop: 'issueYear', order: 'descending'}"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        label="序号"
        width="50"
        align="center"
      >
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.limit + scope.$index + 1}}
        </template>
      </el-table-column>
			<el-table-column
        prop="remark"
        label="备注"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
			<el-table-column prop="benefitsMicrometer" label="福利金额(元)" width="150">
        <template slot-scope="scope">
          <el-tag type="primary">￥{{ scope.row.benefitsMicrometer }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="issueYear"
        label="年份"
        align="center"
        width="150"
				sortable="custom"
        sort-by="issue_year"
        :sort-orders="['ascending', 'descending']"
      ></el-table-column>
      <el-table-column
        prop="issueMonth"
        label="月份"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="issueDate"
        label="福利发放日期"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row.benefitsId)">
            修改
          </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.benefitsId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

		<Pagination
			v-show="totalCount>0"
      :total="totalCount"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getData"
    />

		<!-- 新增或修改节日福利对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <input type="hidden" v-model="form.benefitsId" />
        <el-form-item label="福利金额" prop="benefitsSalary">
          <el-input-number
            style="width: 100%"
            v-model="form.benefitsSalary"
            placeholder="请输入福利金额"
            :min="1"
            :max="99999999.99"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="发放日期" prop="issueDate">
          <el-date-picker
            v-model="form.issueDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择发放日期"
            :editable="false"
            class="el-date-picker-custom"
            :clearable="false"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="submitForm()" :disabled="buttonState.submitDisabled">确 定</el-button>
        <el-button @click.native="cancelHandler()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'HolidayBenefits',
    data() {
      return {
				queryParams: {
					year: -1,
					page: 1,
					limit: 10,
					asc: false
				},
				tableData: null,
				pageTotal: null, // 当前页合计
				total: null, // 总计
				totalCount: 0,
				buttonState: {
					editDisabled: true,
					delDisabled: true,
					submitDisabled: false
				},
				loading: true,
				ids: [],
				// 弹出层标题
				title: '',
				// 是否显示弹出层
				open: false,
				// 表单参数
				form: {},
				// 表单验证规则
				rules: {
					benefitsSalary: [
						{
							required: true,
							message: '请输入正确的工资，范围1-99999999.99',
							trigger: 'blur',
						},
					],
					issueDate: [
						{ required: true, message: '请选择发放日期', trigger: 'blur' },
					],
					remark: [
						{ required: true, message: '请输入备注', trigger: 'blur' },
					],
				},
      };
    },
    created() {
			this.getData();
    },
    methods: {
			// 排序
			sortChange(column, prop, order) {
				if (column.order == 'ascending') {
					this.queryParams.asc = true;
				} else {
					this.queryParams.asc = false;
				}
				this.getData();
			},
			// 提交表单到后台
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						this.buttonState.submitDisabled = true;
						if (!this.form.benefitsId) {
							// 新增
							this.postRequest("/benefits/", this.form).then(() => {
								this.open = false;
								this.buttonState.submitDisabled = false;
								// 新增成功，跳转到最后一页
								this.totalCount += 1;
								let totalPage = Math.ceil(this.totalCount / this.queryParams.limit);
								this.queryParams.page = this.queryParams.page > totalPage ? this.queryParams.page : totalPage
								
								this.getData()
							}).catch(() => {
								this.buttonState.submitDisabled = false;
							})
						} else {
							// 修改
							this.putRequest('/benefits/', this.form).then(() => {
								this.open = false
								this.buttonState.submitDisabled = false;
								this.getData()
							}).catch(() => {
								this.buttonState.submitDisabled = false;
							})
						}
					}
				});
			},
			// 删除节日福利
			handleDelete(benefitsIds) {
				this.$confirm('此操作将永久删除该条节日福利记录是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let id = benefitsIds || this.ids;
					this.deleteRequest(`/benefits/${id}`).then(() => {
						// 判断删除之后页码数是否发生变化
						let totalPage = 0; 
						if (id instanceof Array) {
							// 批量删除
							totalPage = Math.ceil((this.totalCount - id.length) / this.queryParams.limit); // 剩余数据总页数
							this.totalCount -= id.length;
						} else {
							// 单条删除
							totalPage = Math.ceil((this.totalCount - 1) / this.queryParams.limit); // 剩余数据总页数
							this.totalCount -= 1;
						}

						this.queryParams.page = this.queryParams.page > totalPage ? totalPage : this.queryParams.page
						this.queryParams.page = this.queryParams.page < 1 ? 1 : this.queryParams.page

						this.getData()
					})
				}).catch(() => {});
			},
			// 打开修改对话框
			handleUpdate(benefitsId) {
				this.title = "修改节日福利"
				let id = benefitsId || this.ids[0]
				this.getRequest(`/benefits/info/${id}`).then((resp) => {
					this.form = resp.data;
        	this.open = true;
				})
			},
			// 关闭对话框
			cancelHandler() {
				this.open = false
				setTimeout(() => {
					this.reset()
				}, 200)
			},
			// 打开新增节日福利对话框
			handleAdd(){
				this.reset();
				this.open = true;
				this.title = '新增节日福利'
			},
			// 重置表单
			reset() {
				this.form = {
					issueDate: this.parseTime(new Date(), '{yyyy}-{mm}-{dd}'),
				}
				this.resetForm('form')
			},
			// 获取节日福利数据
			getData() {
				this.loading = true
				this.getRequest(`/benefits/${this.queryParams.year}?page=${this.queryParams.page}&limit=${this.queryParams.limit}&asc=${this.queryParams.asc}`).then((resp) => {
					this.tableData = resp.data.list.result;
					this.totalCount = Number(resp.data.total);
					this.pageTotal = resp.data.list.pageTotal;
					this.total = resp.data.list.total;
					this.loading = false;
				})
			},
			// 复选框选择
			handleSelectionChange(val) {
				this.ids = val.map((item) => item.benefitsId)
				if (this.ids.length <= 0) {
					this.buttonState.delDisabled = true
				} else {
					this.buttonState.delDisabled = false
				}

				if (this.ids.length == 1) {
					this.buttonState.editDisabled = false
				} else {
					this.buttonState.editDisabled = true
				}
			},
			getSummaries(param) {
				const { columns } = param

      	const sums = []

				columns.forEach((column, index) => {
					if (index === 2) {
						sums[index] = (
							<div class="footer-body">
								<span class="summary-title">当前页合计</span>
								<span class="border-summary" />
								<span class="summary-title">总计</span>
							</div>
						)
						return
					}
					if (column.property === 'benefitsMicrometer') {
						sums[index] = (
							<div class="footer-body">
								<span class="summary-title">
									<el-tag type="primary">￥{this.pageTotal} 元</el-tag>
								</span>
								<span class="border-summary" />
								<span class="summary-title">
									<el-tag type="primary">￥{this.total} 元</el-tag>
								</span>
							</div>
						)
					} else {
						sums[index] = <div class="border-summary"></div>
					}
				})
				return sums
			}
    },
		computed: {
			years() {
				let options = [
					{
						value: -1,
						label: '全部',
					},
				]
				const year = new Date().getFullYear()
				for (let i = year; i >= 1990; i--) {
					options.push({
						value: i,
						label: i + '年节日福利',
					})
				}

				return options
			}
		}
  }
</script>

<style lang='scss' scoped>

</style>